package com.xin.springcloudconsumer.utils;

import com.xin.springcloudconsumer.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 上传图片
 * Created by zz on 2017/8/12.
 */
@Slf4j
public class UploadUtils {
    public static ResultVO<String> upload(MultipartFile file, HttpServletRequest request, String ROOT){
        int index=file.getOriginalFilename().lastIndexOf(".");
        String fileName="";
        if (index<=-1){
            fileName=KeyUtil.genUniqueKey()+".png";
        }
        else {
            String orgname=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            fileName= KeyUtil.genUniqueKey()+orgname;
        }
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream buffStream =
                        new BufferedOutputStream(new FileOutputStream(new File(ROOT + fileName)));
                buffStream.write(bytes);
                buffStream.close();
                ResultVO resultVO=new ResultVO();
                resultVO.setCode(0);
                String photoUrl=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+fileName;
                resultVO.setData(photoUrl);
//            return "\"{errno:0,data:['"+request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/myboke/"+file.getOriginalFilename()+"'] }\"";
                return  resultVO;
            } catch (Exception e) {
                log.info("【上传图片失败】");
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }

    }
}
